#!D:/CODE/python
# -*- coding: utf-8 -*-
# @Time : 2020/5/20 23:13
# @Author : Alexdong
# @Site : 
# @File : 文件下载器_服务器.py
# @Software: PyCharm
# Functional description:

from socket import *
import sys

def get_file_content(file_name):
    '''获取文件内容'''
    try:
        with open(file_name, 'rb') as f:
            content = f.read()
        return content
    except:
        print("没有下载的文件")

def send_file_2_client(new_client_socket, client_add):
    # 接收要下载的文件名
    file_name = new_client_socket.recv(1024)
    print("客户端(%s)要下载的文件是：%s" % (str(client_add), file_name))
    file_content = None
    # 打开文件，读取数据
    file_content = get_file_content(file_name)

    if file_content:
        new_client_socket.send(file_content)


def main():
    tcp_server_socket = socket(AF_INET, SOCK_STREAM)
    tcp_server_socket.bing('', 7898)
    tcp_server_socket.listen(128)

    while True:
        # accept接受
        # 服务器的监听会给客户端找另一个套接字，然后断开该监听，继续监听新客户端
        # 获得客户端信息，套接字,ip和端口的元组
        print("等待")
        new_client_socket, client_address = tcp_server_socket.accept()

        send_file_2_client(new_client_socket,client_address)
        # 关闭某客户端套接字
        new_client_socket.close()
    # 关闭监听套接字
    tcp_server_socket.close()


if __name__ == "__main__":
    main()
